package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.util.FormatUtil;

/**
 * Export data between time range
 * @author Z.J
 *
 */
public class ExportAsyncTask extends AsyncTask<Date, String, String> {

	private AccDBHelper dbHelper;
	private SQLiteDatabase db;
	private Context context;
	
	public ExportAsyncTask(Context context) {
		dbHelper = new AccDBHelper(context);
		this.context = context;
	}

	@Override
	protected String doInBackground(Date... params) {
		// get params
		long from = params[0].getTime();
		long to = params[1].getTime();
		
		// query data from db
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT * FROM " 
									+ DBConstants.V_RECORD
									+ " WHERE datatime >= ? and datatime < ?"
									+ " ORDER BY datatime ASC"
									, new String[] {from + "", to + ""});
		
		// prepare the filename
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(from);
		
		StringBuilder fileName = new StringBuilder();
		fileName.append(c.get(Calendar.YEAR))
				.append(c.get(Calendar.MONTH) + 1)
				.append(c.get(Calendar.DAY_OF_MONTH))
				.append("-");
		
		c.setTimeInMillis(to);
		fileName.append(c.get(Calendar.YEAR))
				.append(c.get(Calendar.MONTH) + 1)
				.append(c.get(Calendar.DAY_OF_MONTH))
				.append(".csv");
		
		// get external storage path
		File dir = context.getExternalFilesDir(null);
		File destFile = new File(dir, fileName.toString());
		try {
			// create the exported file
			if (destFile.exists()) {
				destFile.delete();
				destFile.createNewFile();
			}
			
			BufferedWriter bw = new BufferedWriter(new FileWriter(destFile));
			StringBuilder sb  = new StringBuilder();
			while (cursor.moveToNext()) {
				Long millis 	= cursor.getLong(cursor.getColumnIndex(DBConstants.RECORD_DATATIME));
				String item 	= cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_ITEM));
				String category = cursor.getString(cursor.getColumnIndex(DBConstants.RECORD_CATEGORY));
				int price		= cursor.getInt(cursor.getColumnIndex(DBConstants.RECORD_PRICE));
				
				sb.setLength(0);
				sb.append(FormatUtil.formatDateToMMddyyyy(new Date(millis)))
				  .append(",")
				  .append(category)
				  .append(",")
				  .append(item)
				  .append(",")
				  .append(price)
				  .append("\n");
				
				bw.write(sb.toString());
			}
			bw.close();
		} catch (FileNotFoundException e) {
			Log.e("ZJ", "Export Async Task file not found. " + e.getMessage());
		} catch (IOException e) {
			Log.e("ZJ", "Export Async Task IOException." + e.getMessage());
		}
		
		cursor.close();
		db.close();
		dbHelper.close();
		return destFile.getAbsolutePath();
	}

	@Override
	protected void onPostExecute(String result) {
		Toast.makeText(context, "Export file: " + result, Toast.LENGTH_SHORT).show();
	}
}
